"""
商品和评价相关API
"""
from fastapi import APIRouter, Depends, HTTPException
from fastapi.responses import JSONResponse
from sqlalchemy.orm import Session
from typing import List
from decimal import Decimal
import pandas as pd
import os
from datetime import datetime
import random

from database import get_db
from models.models import User
from models.goods_models import Goods, GoodsReview
from schemas.goods import GoodsResponse, GoodsReviewRequest, GoodsReviewResponse, RecommendationResponse
from routers.dependencies import get_current_user
from config.settings import settings
try:
    import dashscope
    from dashscope import Generation
    DASHSCOPE_AVAILABLE = True
except ImportError:
    DASHSCOPE_AVAILABLE = False
    Generation = None

router = APIRouter(prefix="/api/goods", tags=["商品"])

# CSV文件路径
CSV_FILE_PATH = "data/goods_reviews.csv"

IMAGE_POOL = [
    "https://images.unsplash.com/photo-1503602642458-232111445657?auto=format&fit=crop&w=800&q=60",
    "https://images.unsplash.com/photo-1512496015851-a90fb38ba796?auto=format&fit=crop&w=800&q=60",
    "https://images.unsplash.com/photo-1505740420928-5e560c06d30e?auto=format&fit=crop&w=800&q=60",
    "https://images.unsplash.com/photo-1526170375885-4d8ecf77b99f?auto=format&fit=crop&w=800&q=60",
    "https://images.unsplash.com/photo-1517686469429-8bdb88b9f907?auto=format&fit=crop&w=800&q=60",
    "https://images.unsplash.com/photo-1513708925888-6baf1708d2d4?auto=format&fit=crop&w=800&q=60",
    "https://images.unsplash.com/photo-1526178618718-507ef42542b3?auto=format&fit=crop&w=800&q=60",
    "https://images.unsplash.com/photo-1517336714731-489689fd1ca8?auto=format&fit=crop&w=800&q=60",
]
CATEGORIES = ["美妆", "服饰", "家居", "数码", "运动", "母婴", "零食", "饰品"]


def ensure_csv_directory():
    """确保CSV目录存在"""
    os.makedirs(os.path.dirname(CSV_FILE_PATH), exist_ok=True)
    
    # 如果CSV文件不存在，创建并写入表头
    if not os.path.exists(CSV_FILE_PATH):
        df = pd.DataFrame(columns=["userid", "goodsid", "score", "Time"])
        df.to_csv(CSV_FILE_PATH, index=False, encoding="utf-8-sig")


def save_review_to_csv(user_id: int, goods_id: int, score: Decimal, time: datetime):
    """保存评价到CSV文件"""
    ensure_csv_directory()
    
    # 读取现有数据
    if os.path.exists(CSV_FILE_PATH):
        df = pd.read_csv(CSV_FILE_PATH, encoding="utf-8-sig")
    else:
        df = pd.DataFrame(columns=["userid", "goodsid", "score", "Time"])
    
    # 添加新数据
    new_row = {
        "userid": user_id,
        "goodsid": goods_id,
        "score": float(score),
        "Time": time.strftime("%Y-%m-%d %H:%M:%S")
    }
    df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True)
    
    # 保存到CSV
    df.to_csv(CSV_FILE_PATH, index=False, encoding="utf-8-sig")


@router.post("/seed")
async def seed_goods(
    token: str,
    count: int = 50,
    db: Session = Depends(get_db)
):
    """
    一次性初始化商品数据（仅管理员令牌可调用）
    使用方式：
      POST /api/goods/seed?token=<settings.SECRET_KEY>&count=50
    """
    if token != settings.SECRET_KEY:
        raise HTTPException(status_code=403, detail="无权限")
    try:
        existing = db.query(Goods).count()
        if existing >= count:
            return {"inserted": 0, "message": f"已有 {existing} 条，跳过"}
        items = []
        for i in range(count):
            price = round(random.uniform(19.9, 999.0), 2)
            items.append(Goods(
                name=f"优选好物 {i+1} 号",
                description=f"第 {i+1} 件优选好物，质感出众，性价比高，日常必备。",
                price=Decimal(str(price)),
                image_url=random.choice(IMAGE_POOL),
                category=random.choice(CATEGORIES),
                status=1,
                stock=random.randint(5, 300)
            ))
        db.add_all(items)
        db.commit()
        return {"inserted": len(items)}
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=str(e))


def score_review_with_llm(content: str) -> Decimal:
    """
    使用LLM对评价内容进行评分（0-10分）
    """
    if not DASHSCOPE_AVAILABLE:
        # 如果DashScope不可用，返回默认值
        return Decimal("5.0")
    
    prompt = f"""
请对以下商品评价内容进行评分，评分范围是0-10分，其中：
- 0-3分：非常不满意，有严重问题
- 4-5分：不满意，有明显缺点
- 6-7分：一般，基本满意但有不足
- 8-9分：满意，质量不错
- 10分：非常满意，完美

评价内容：
{content}

请只返回一个0-10之间的数字分数，不要返回其他内容。
"""
    
    try:
        resp = Generation.call(
            model="qwen-turbo",
            messages=[{"role": "user", "content": prompt}],
            result_format='message'
        )
        
        if resp.status_code == 200:
            output = resp.output
            if hasattr(output, 'choices') and output.choices:
                response_text = output.choices[0].message.content
            elif hasattr(output, 'text'):
                response_text = output.text
            else:
                response_text = str(output)
            
            # 提取数字
            score_str = "".join(filter(str.isdigit, str(response_text)))
            if score_str:
                score = float(score_str)
                # 限制在0-10之间
                score = max(0, min(10, score))
                return Decimal(str(round(score, 1)))
        
        # 如果无法提取分数，返回默认值5.0
        return Decimal("5.0")
    except Exception as e:
        print(f"[评分] LLM评分失败: {e}")
        # 评分失败时返回默认值
        return Decimal("5.0")


@router.get("/", response_model=List[GoodsResponse])
async def get_all_goods(
    limit: int = 20,
    offset: int = 0,
    db: Session = Depends(get_db)
):
    """获取所有商品列表"""
    goods = db.query(Goods).filter(
        Goods.status == 1
    ).limit(limit).offset(offset).all()
    return goods


@router.get("/{goods_id}", response_model=GoodsResponse)
async def get_goods_detail(
    goods_id: int,
    db: Session = Depends(get_db)
):
    """获取商品详情"""
    goods = db.query(Goods).filter(Goods.id == goods_id).first()
    if not goods:
        raise HTTPException(status_code=404, detail="商品不存在")
    return goods


@router.get("/{goods_id}/reviews", response_model=List[GoodsReviewResponse])
async def get_goods_reviews(
    goods_id: int,
    limit: int = 20,
    offset: int = 0,
    db: Session = Depends(get_db)
):
    """获取商品评价列表"""
    reviews = db.query(GoodsReview).filter(
        GoodsReview.goods_id == goods_id
    ).order_by(
        GoodsReview.created_at.desc()
    ).limit(limit).offset(offset).all()
    return reviews


@router.post("/{goods_id}/review", response_model=GoodsReviewResponse)
async def create_review(
    goods_id: int,
    request: GoodsReviewRequest,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    创建商品评价
    
    1. 使用LLM对评价内容进行评分（0-10分）
    2. 保存评价到数据库
    3. 保存评价到CSV文件（用于推荐系统）
    """
    # 检查商品是否存在
    goods = db.query(Goods).filter(Goods.id == goods_id).first()
    if not goods:
        raise HTTPException(status_code=404, detail="商品不存在")
    
    # 使用LLM对评价内容进行评分
    score = score_review_with_llm(request.content)
    
    # 创建评价记录
    review = GoodsReview(
        user_id=current_user.id,
        goods_id=goods_id,
        content=request.content,
        score=score
    )
    db.add(review)
    db.commit()
    db.refresh(review)
    
    # 保存到CSV文件
    save_review_to_csv(
        user_id=current_user.id,
        goods_id=goods_id,
        score=score,
        time=review.created_at
    )
    
    return review


@router.get("/recommendations/list", response_model=List[RecommendationResponse])
async def get_recommendations(
    limit: int = 10,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """
    获取商品推荐列表
    
    使用协同过滤算法：
    1. 获取用户-物品索引（用户已评价的商品）
    2. 获取用户-用户索引（相似用户）
    3. 找到相似度最高的用户
    4. 获取该用户的商品
    5. 取差集（推荐用户没看过的）
    """
    try:
        # 检查Goods表是否存在
        try:
            from tasks.recommendation import get_recommendations as get_recs
        except ImportError as e:
            print(f"[推荐API] 导入推荐模块失败: {e}")
            return []
        
        # 获取推荐商品ID列表
        try:
            recommended_goods_ids = get_recs(current_user.id, limit)
        except Exception as e:
            print(f"[推荐API] 获取推荐商品ID失败: {e}")
            import traceback
            traceback.print_exc()
            return []
        
        if not recommended_goods_ids:
            # 如果没有推荐，返回空列表
            return []
        
        # 查询商品信息
        try:
            goods_list = db.query(Goods).filter(
                Goods.id.in_(recommended_goods_ids),
                Goods.status == 1
            ).all()
        except Exception as e:
            print(f"[推荐API] 查询商品失败: {e}")
            # 可能是表不存在，返回空列表
            return []
        
        # 构建响应（保持推荐顺序）
        result = []
        goods_dict = {g.id: g for g in goods_list}
        for gid in recommended_goods_ids:
            if gid in goods_dict:
                goods = goods_dict[gid]
                result.append(RecommendationResponse(
                    goods_id=goods.id,
                    name=goods.name,
                    description=goods.description,
                    price=goods.price,
                    image_url=goods.image_url,
                    category=goods.category,
                    score=None
                ))
        
        return result
    except Exception as e:
        import traceback
        traceback.print_exc()
        print(f"[推荐API] 获取推荐失败: {e}")
        # 返回空列表而不是抛出异常
        return []

